/**
 * @author 2019/7/23 9:37 by 刘赵强
 * join() 的作用：让主线程等待子线程结束之后才能继续运行，首先先来看下以采集为案例的代码，统计采集所消耗的时长
 * 在start方法下添加join操作，运行main方法，发现不管那个线程先执行，结果都是5000毫秒以上，
 * 因为主线程main接收到了M1，M2，M3三个线程的join指令，这个时候主线程则会处于阻塞状态，直到子线程执行完毕后才会继续执行下去...
 **/
public class ThreadJoin {

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread t1 = new Thread(new CaptureRunnable("M1", 50_000L));
        Thread t2 = new Thread(new CaptureRunnable("M2", 30_000L));
        Thread t3 = new Thread(new CaptureRunnable("M3", 20_000L));
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t3.join();
        t2.join();
        Thread.yield();
        System.out.println("采集完成,消耗 " + (System.currentTimeMillis() - startTime));
    }
}


class CaptureRunnable implements Runnable {
    private String machineName;
    private Long spendTime;

    public CaptureRunnable(String machineName, Long spendTime) {
        this.machineName = machineName;
        this.spendTime = spendTime;
    }

    @Override
    public void run() {
        try {
            System.out.println(machineName + "开始采集");
            Thread.sleep(spendTime);
            System.out.println(machineName + "采集完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}